# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：用户视图
"""
import re
from . import user_blue, user_api
from flask import request
from api.utils.response import to_response
from api.models import User, Role
from api import db
from api.utils.tokens import generate_auth_token, login_required, verify_auth_token
from api.utils import constants
from ..utils.baseResource import BaseResource
from flask import current_app


@user_blue.route("/login", methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not all([username, password]):
        return to_response(10000)

    try:
        user = User.query.filter(User.name == username).first()
    except Exception as e:
        print(e)
        return to_response(20000)

    if not user:
        return to_response(10017)

    if not user.check_password(password):
        return to_response(10011)

    current_app.celery.send_task('add_together', args=[1, 2])
    token = generate_auth_token(user.id, constants.TOKEN_EXPIRATION_TIME)

    return to_response(200, data={'token': token})


class UserResource(BaseResource):
    def get(self):
        user_id = request.args.get('id', None)
        if not user_id:
            return to_response(10016)
        try:
            user = User.query.filter(User.id == user_id).first()
        except Exception as e:
            return to_response(10020)

        if not user:
            return to_response(10017)
        return to_response(200, data=user.to_dict())

    def post(self):
        name = request.json.get('name', None)
        password = request.json.get('password', None)
        confirm_password = request.json.get('confirm_password', None)
        nick_name = request.json.get('nick_name', None)
        phone = request.json.get('phone', None)
        email = request.json.get('email', None)
        role_name = request.json.get('role_name', None)

        if not all([name, password, confirm_password]):
            return to_response(10000)

        if password != confirm_password:
            return to_response(10011, msg='两次密码不一致！')

        if len(name) < 3:
            return to_response(10011)

        if User.query.filter(User.name == name).first():
            return to_response(10012, msg='用户名不能重复！')

        if not re.match(r'^1[3456789]\d{9}$', phone):
            return to_response(10013)

        if User.query.filter(User.phone == phone).first():
            return to_response(10012, msg='手机号不能重复！')

        if not re.match(r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$', email):
            return to_response(10014)

        if role_name:
            if not Role.query.filter(Role.id == role_name).first():
                return to_response(10015, msg='角色不存在！')

        user = User()
        user.name = name
        user.password = password
        user.nick_name = nick_name
        user.phone = phone
        user.email = email
        user.rid = role_name
        try:
            db.session.add(user)
            db.session.commit()
            return to_response(200, data=user.to_dict())
        except Exception as e:
            print(e)
            return to_response(20000)

    def put(self):
        id = request.json.get('id', None)
        nick_name = request.json.get('nick_name', None)
        phone = request.json.get('phone', None)
        email = request.json.get('email', None)
        role_name = request.json.get('role_name', None)
        if not id:
            return to_response(10000)
        try:
            user = User.query.filter(User.id == id).first()
        except Exception as e:
            return to_response(10020)
        if not user:
            return to_response(10017)
        if phone:
            if not re.match(r'^1[3456789]\d{9}$', phone):
                return to_response(10013)
            if User.query.filter(User.phone == phone).first():
                return to_response(10012, msg='手机号不能重复！')
        if role_name:
            if not Role.query.filter(Role.id == role_name).first():
                return to_response(10015, msg='角色不存在！')

        try:
            user.nick_name = nick_name
            user.phone = phone
            user.email = email
            user.rid = role_name
            db.session.commit()
            return to_response(200, data=user.to_dict(), msg='修改用户信息成功!')
        except Exception as e:
            print(e)
            return to_response(10020)

    def delete(self):
        id = request.args.get('id', None)
        if not id:
            return to_response(10000)
        try:
            user = User.query.filter(User.id == id).first()
        except Exception as e:
            return to_response(10020)
        if not user:
            return to_response(10017)
        try:
            db.session.delete(user)
            db.session.commit()
            return to_response(200, msg='删除成功!')
        except Exception as e:
            print(e)
            return to_response(10020)


class UserListResource(BaseResource):
    def post(self):
        name = request.args.get('name')
        page = request.args.get('page') if request.args.get('page') else 1
        psize = request.args.get('psize') if request.args.get('psize') else 2
        if name:
            users_page = User.query.order_by(User.create_time.desc()).filter(User.name.like('%' + name + '%')).paginate(
                page=int(page), per_page=int(psize))

        else:
            users_page = User.query.order_by(User.create_time.desc()).paginate(page=int(page), per_page=int(psize))

        data = {
            'page': page,
            'totalPage': users_page.total,
            'users': [user.to_dict() for user in users_page.items]
        }

        return to_response(200, data=data, msg='用户列表查询成功!')


user_api.add_resource(UserResource, '/user')
user_api.add_resource(UserListResource, '/user_list')


@user_blue.route("/user_token")
@login_required
def user_token():
    token = request.args.get('token', None)
    if not token:
        return to_response(10000)

    try:
        user_id = verify_auth_token(token, constants.TOKEN_EXPIRATION_TIME)
    except Exception as e:
        return to_response(20000)

    if not user_id:
        return to_response(10016)
    try:
        user = User.query.filter(User.id == user_id).first()
    except Exception as e:
        return to_response(10020)

    if not user:
        return to_response(10017)
    return to_response(200, data=user.to_dict())


@user_blue.route("/reset")
@login_required
def reset():
    id = request.args.get('id', None)
    if not id:
        return to_response(10000)

    try:
        user = User.query.filter(User.id == id).first()
    except Exception as e:
        return to_response(10020)

    if not user:
        return to_response(10017)

    try:
        user.password = '123456'
        db.session.commit()
    except Exception as e:
        return to_response(10020)

    return to_response(200, msg='重置密码成功！')
